import {ChangeDetectorRef, Component, OnInit} from '@angular/core';
import {NzResizeEvent} from 'ng-zorro-antd/resizable';
import {editor} from 'monaco-editor';
// eslint-disable-next-line  @typescript-eslint/no-explicit-any
declare const monaco: any;
import nightowl from "../course/NightOwl";
import {MarkdownService} from 'ngx-markdown';
import {ActivatedRoute} from '@angular/router';
import {Course, CourseCheck, CoursePage, CourseTask} from '../course/Course';
import {Title} from '@angular/platform-browser';
import {CourseLoaderService} from '../course/course-loader.service';
import {from} from 'rxjs';

@Component({selector: 'app-creator', templateUrl: './creator.component.html', styleUrls: ['./creator.component.scss']})
export class CreatorComponent implements OnInit {
    constructor(private cdr : ChangeDetectorRef, private route : ActivatedRoute, private title : Title, private courseLoader : CourseLoaderService, private markdownService : MarkdownService) {}
    course : Course = new Course('', '', []);
    pageIndex = 0;
    page : CoursePage = new CoursePage('', '', '', '', []);
    task : CourseTask = new CourseTask('', '', new CourseCheck(1, '', ''), new CourseCheck(1, '', ''));
    ngOnInit(): void {
        const id = this.route.snapshot.paramMap.get('id')as string;
        // 修改链接为默认在新标签页打开
        const linkRenderer = this.markdownService.renderer.link;
        this.markdownService.renderer.link = (href, title, text) => {
            const html = linkRenderer.call(this.markdownService.renderer, href, title, text);
            return html.replace(/^<a /, '<a target="_blank" rel="nofollow" ');
        };
        from(this.courseLoader.get(id)).subscribe(course => {
            if (course) {
                this.course = course;
                this.pageIndex = 0;
                this.page = this.course.page[this.pageIndex];
                this.selectedTaskIndex = 0;
                this.currentTaskTextArea = this.task.title + '\n' + this.task.description;
                this.task = this.page.task[this.selectedTaskIndex];
                this.title.setTitle(this.course.name);
            } else { // TODO 错误处理
            }
        })
    }
    animationId = -1;
    editors : {
        [key : string]: editor.IStandaloneCodeEditor
    } = {};
    onResize({col} : NzResizeEvent): void {
        cancelAnimationFrame(this.animationId);
        this.animationId = requestAnimationFrame(() => {
            this.col = col !;
        });
        Object.values(this.editors).forEach(x => x.layout());
    }
    // 从markdown获得可能的标题
    extractTitle(markdown : string): string {
        const splits = markdown.split('\n').filter(x => x.trim() !== '');
        if (splits.length !== 0) {
            return splits[0].replace('#', '').trim();
        }
        return '新页面';
    }
    markdown = '';
    tabSelectedIndex = 0;
    editorLoaded: {[name: string]: boolean} = {};
    onEditorInit(name : string, e : editor.ICodeEditor | editor.IEditor): void { // 这里的转换不太行
        this.editors[name] = e as editor.IStandaloneCodeEditor;
        this.editorLoaded[name] = true;
        monaco.editor.defineTheme('nightowl', nightowl);
        monaco.editor.setTheme('nightowl');
        if (name === 'markdown') {
            this.editors['markdown'].getModel() ?. onDidChangeContent(event => {
                this.page.name = this.extractTitle(this.page.markdown);
                from(this.courseLoader.save(this.course)).subscribe(x=>x);
            });
        }
        else{
          this.editors[name].getModel() ?. onDidChangeContent(event => {
            from(this.courseLoader.save(this.course)).subscribe(x=>x);
        });
        }
    }
    col = 10;
    onTabSelectedIndexChange($event : number) {}
    selectedTaskIndex = 0;
    currentTaskTextArea = '';
    onTaskSelectedIndexChange($event : number) {
        this.task = this.page.task[$event];
        this.currentTaskTextArea = this.task.title + '\n' + this.task.description;
    }
    newTaskTab() {
        this.page.task.push(new CourseTask('新任务', '', new CourseCheck(1, '', ''), new CourseCheck(1, '', '')));
        this.selectedTaskIndex = this.page.task.length - 1;
    }
    taskTextChange() {
        const splits = this.currentTaskTextArea.split('\n', 2);
        this.task.title = splits[0];
        if (splits.length > 1) {
            this.task.description = splits[1];
        } else {
            this.task.description = '';
        }
        this.cdr.detectChanges();
    }
    closeTaskTab($event : {
        index: number
    }) {
        this.page.task.splice($event.index, 1);
        if (this.selectedTaskIndex >= this.page.task.length) {
            this.selectedTaskIndex --;
        }
        this.task = this.page.task[this.selectedTaskIndex];
    }
    // 翻页
    nextPage() {
        if (this.pageIndex === this.course.page.length - 1) {
            this.selectedTaskIndex = 0;
            this.task = new CourseTask('新任务', '', new CourseCheck(1, '', ''), new CourseCheck(1, '', ''));
            this.selectedTaskIndex = 0;
            this.course.page.push(new CoursePage('新页面', '', '', '', [this.task]));
        } else {
            this.selectedTaskIndex = 0;
        }
        this.page = this.course.page[++ this.pageIndex]
        this.onTaskSelectedIndexChange(0);
    }
    lastPage() {
        this.page = this.course.page[-- this.pageIndex];
        this.selectedTaskIndex = 0;
        this.onTaskSelectedIndexChange(0);
    }
    deletePage() {
        this.course.page.splice(this.pageIndex, 1);
        if (this.pageIndex > 0) {
            this.lastPage();
        } else {
            this.page = this.course.page[0];
            this.selectedTaskIndex = 0;
            this.onTaskSelectedIndexChange(0);
        }
    }
    // 修改运行次数时触发
    onRunTimeChange(state: string, value: number) {
      from(this.courseLoader.save(this.course)).subscribe(x=>x);
    }
    // TODO 给creator添加运行功能
}
